package com.example.yyy

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.viewpager.widget.PagerAdapter

//ViewPager适配器

class ViewPagerAdapter (private val context: Context,private val info:MutableList<GoodsInfo>):PagerAdapter() {

    private val views = mutableListOf<ImageView>()

    init {
        for (i in info){
            val view = ImageView(context)
            view.layoutParams = ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT)
            view.setImageResource(i.img)
            view.scaleType = ImageView.ScaleType.FIT_CENTER
            views.add(view)
        }
    }

    //判断页面是否已加入适配器
    override fun isViewFromObject(view: View, `object`: Any): Boolean = (view===`object`)//引用相等

    //获取页面数
    override fun getCount(): Int = info.size

    //回收页面
    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(views[position])
    }

    //实例化每个页面
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        container.addView(views[position])
        return views[position]
    }

    //获取页面标题，要跟PageTabString配合使用
    override fun getPageTitle(position: Int): CharSequence? =info[position].name
}